package com.app.teaware.stock;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.teaware.R;
import com.app.teaware.basis.BasisActivity;
import com.app.teaware.basis.Constants;
import com.app.teaware.bean.BasisBean;
import com.app.teaware.bean.LoginBean;
import com.app.teaware.bean.StockListBean;
import com.app.teaware.bean.StockListData;
import com.app.teaware.dialog.ResetKWDialog;
import com.app.teaware.util.MyUtils;
import com.app.teaware.util.UHFUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import my.MathUtils;
import my.http.MyHttpListener;
import my.http.MyHttpUtils;
import my.http.MyParams;

public class ResetWareActivity extends BasisActivity {


    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    @BindView(R.id.edit_kw)
    EditText edit_kw;
    StockListBean listBean;
    MyAdapterList mAdapter;
    Calendar calendar;
    ResetKWDialog dialog;

    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.reset_ware_activity);
        setTitle("移库");
        setTitleLeftButton(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
    }

    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            if(!Constants.ACTION_UHF_RESULT_SEND.equals(action))
                return ;
            Parcelable[] tagInfos =  intent.getParcelableArrayExtra(Constants.EXTRA_TAG_INFO);
            String qrcode = UHFUtil.getEPCId(tagInfos).trim().toUpperCase(Locale.ROOT);
            if(dialog != null){
                dialog.setKW(qrcode);
            }else {
                edit_kw.setText(qrcode);
                getList();
            }
        }//end onReceiver
    };

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        listBean = new StockListBean();
        calendar = Calendar.getInstance();
    }


    private boolean httpIsFinish = true;
    private void getList(){
        if(TextUtils.isEmpty(edit_kw.getText().toString())){
            showToast("请先获取库位码");
            return;
        }
        if(!httpIsFinish) return;
        httpIsFinish = false;
        showLoading();
        MyParams params = new MyParams();
        params.put("aid",LoginBean.getInstance().getAcode());
        params.put("wms",edit_kw.getText().toString());

        MyHttpUtils.get(Constants.URL_STOCK_GET_CHECK_STOCK_BY_LOC, params, new MyHttpListener() {
                    @Override
                    public void onSuccess(int httpWhat, Object result) {
                        if (isFinishing()) return;
                        listBean = (StockListBean) result;
                        setListView();
                    }

                    @Override
                    public void onFailure(int httpWhat, Object result) {
                        super.onFailure(httpWhat, result);
                        dismissProgress();
                        listBean.getList().clear();
                        setListView();
                    }

                    @Override
                    public void onFinish(int httpWhat) {
                        httpIsFinish = true;
                        dismissProgress();
                    }
                },
                0, StockListBean.class);
    }

    private void setListView() {
        if (mAdapter == null) {
            mAdapter = new MyAdapterList();
            mRecyclerView.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder>
    {
        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.reset_ware_list_item, viewGroup, false);
            return new ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            int count = listBean == null ? 0 : listBean.getList().size();
            return count;
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.text_code)
            public TextView text_code;
            @BindView(R.id.list_item)
            public View list_item;
            @BindView(R.id.text_name)
            public TextView text_name;
            @BindView(R.id.text_specs)
            public TextView text_specs;
            @BindView(R.id.text_unit)
            public TextView text_unit;
            @BindView(R.id.text_num)
            public TextView text_num;
            @BindView(R.id.text_weight)
            public TextView text_weight;
            @BindView(R.id.text_kw)
            public TextView text_kw;
            @BindView(R.id.text_qrcode)
            public TextView text_qrcode;

            @BindView(R.id.text_weight_fact)
            public TextView text_weight_fact;
            @BindView(R.id.btn_edit)
            public TextView btn_edit;


            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                StockListData data = listBean.getList().get(position);
                MyUtils.setNotNullText(text_code, data.getGno());
                MyUtils.setNotNullText(text_name, data.getGna());
                MyUtils.setNotNullText(text_specs, data.getGsp());
                MyUtils.setNotNullText(text_unit, data.getGun());
                MyUtils.setNotNullText(text_num, data.getGnu1());
                MyUtils.setNotNullText(text_weight, data.getGwtp());
                MyUtils.setNotNullText(text_kw, data.getWms1());
                MyUtils.setNotNullText(text_qrcode, data.getRfid());
                MyUtils.setNotNullText(text_weight_fact, MathUtils.div(MathUtils.multiply(data.getGwtp(),data.getGnu1()),"1000"));
                if(data.isSelect()){
                    list_item.setBackgroundResource(R.drawable.base_blue_light_roundcorner);
                }else {
                    list_item.setBackgroundResource(R.drawable.base_white_round);
                }
                btn_edit.setTag(data);
                list_item.setTag(data);
            }
            @OnClick(R.id.btn_edit)
            void onBtnClick(View view){
                StockListData data = (StockListData) view.getTag();
                dialog= new ResetKWDialog(mContext,data, new ResetKWDialog.OnEditPostListener() {
                    @Override
                    public void onSubmit(String kw) {
                        dialog = null;
                        MyParams params = new MyParams();
                        showProgress();
                        params.put("aid",LoginBean.getInstance().getAcode());
                        params.put("cid",data.getCid());
                        params.put("mm", calendar.get(Calendar.MONTH) + 1);        //当前月
                        params.put("yy", calendar.get(Calendar.YEAR));      //当前年
                        params.put("rfid",data.getRfid()); //箱码
                        params.put("wms1",data.getWms1()); //原来库位
                        params.put("wms2",kw); //箱码
                        MyHttpUtils.post(Constants.URL_LOCATION_UPDATE, params, new MyHttpListener() {
                                    @Override
                                    public void onSuccess(int httpWhat, Object result) {
                                        if (isFinishing()) return;
                                        BasisBean basisBean = (BasisBean) result;
                                        showToast(basisBean.getStatusInfo());
                                        getList();
                                    }

                                    @Override
                                    public void onFailure(int httpWhat, Object result) {
                                        super.onFailure(httpWhat, result);
                                    }

                                    @Override
                                    public void onFinish(int httpWhat) {
                                        dismissProgress();
                                    }
                                },
                                0, BasisBean.class);
                    }
                    @Override
                    public void onCancel() {
                        dialog = null;
                        setListView();
                    }
                });
                dialog.show();
            }

            @OnClick(R.id.list_item)
            void onItemClick(View view){
                StockListData data = (StockListData) view.getTag();
                data.setSelect(!data.isSelect());
                notifyItemChanged(getAdapterPosition());
            }
        }
    }



    @Override
    protected void onPause() {
        super.onPause();
        unRegisterResultReceiver();
    }


    @Override
    protected void onResume() {
        super.onResume();
        registerResultReceiver();
    }

    private void registerResultReceiver() {
        try {
            IntentFilter iFilter = new IntentFilter(Constants.ACTION_UHF_RESULT_SEND);
            mContext.registerReceiver(mResultReceiver, iFilter);
        } catch (Exception e) {
        }

    }

    private void unRegisterResultReceiver() {
        try {
            mContext.unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
        }
    }


    @OnClick(R.id.btn_tz)
    public void tochange(){
        ArrayList<StockListData> sumitArr = listBean.getSelectedList();
        if(sumitArr == null || sumitArr.size()<1){
            showToast("请先选择货品");
            return;
        }

        dialog= new ResetKWDialog(mContext, new ResetKWDialog.OnEditPostListener() {
            @Override
            public void onSubmit(String kw) {
                dialog = null;
                submit(kw,sumitArr);
            }
            @Override
            public void onCancel() {
                dialog = null;
            }
        });
        dialog.show();

    }

    int position = 0;
    public void submit(String wms, ArrayList<StockListData> sumitArr){
        showProgress();
        position = 0;
        for (StockListData data : sumitArr){
            MyParams params = new MyParams();
            params.put("aid",LoginBean.getInstance().getAcode());
            params.put("cid",data.getCid());
            params.put("mm", calendar.get(Calendar.MONTH) + 1);        //当前月
            params.put("yy", calendar.get(Calendar.YEAR));      //当前年
            params.put("rfid",data.getRfid()); //箱码
            params.put("wms1",data.getWms1()); //原来库位
            params.put("wms2",wms); //箱码
            MyHttpUtils.post(Constants.URL_LOCATION_UPDATE, params, new MyHttpListener() {
                        @Override
                        public void onSuccess(int httpWhat, Object result) {
                            if (isFinishing()) return;
                            BasisBean basisBean = (BasisBean) result;
                            position++;
                            if(position == sumitArr.size()){
                                dismissProgress();
                                getList();
                            }
                        }

                        @Override
                        public void onFailure(int httpWhat, Object result) {
                            if (isFinishing()) return;
                            super.onFailure(httpWhat, result);
                            dismissProgress();
                        }

                        @Override
                        public void onFinish(int httpWhat) {
                        }
                    },
                    0, BasisBean.class);
        }

    }

}
